import * as vscode from 'vscode';
import * as path from 'path';

export class WebviewManager {
    private panel: vscode.WebviewPanel | null = null;
    private context: vscode.ExtensionContext;

    constructor(context: vscode.ExtensionContext) {
        this.context = context;
    }

    updatePreview(outputFile: string, renderTime: number, quality: string, sceneName: string, filePath: string) {
        if (!this.panel) {
            this.panel = vscode.window.createWebviewPanel(
                'manimPreview',
                'Manim Preview',
                vscode.ViewColumn.Two,
                { enableScripts: true, localResourceRoots: [vscode.Uri.file(path.join(this.context.extensionPath, 'media'))] }
            );
            this.panel.onDidDispose(() => {
                this.panel = null;
            });
        }

        const webview = this.panel.webview;
        webview.html = this.getWebviewContent(outputFile, renderTime, quality, sceneName, filePath);

        webview.onDidReceiveMessage((message) => {
            if (message.type === 'qualityChanged') {
                vscode.window.showInformationMessage(`重新渲染以质量: ${message.quality}`);
                // 这里可以添加重新渲染逻辑，调用runCommand
            }
        });
    }

    private getWebviewContent(outputFile: string, renderTime: number, quality: string, sceneName: string, filePath: string) {
        const videoUri = this.panel!.webview.asWebviewUri(vscode.Uri.file(path.join(this.context.extensionPath, outputFile)));
        return `
            <html>
            <body>
                <video width="100%" controls>
                    <source src="${videoUri}" type="video/mp4">
                    您的浏览器不支持视频播放。
                </video>
                <p>渲染时长: ${renderTime} 秒</p>
                <label for="quality">清晰度:</label>
                <select id="quality" onchange="qualityChanged(this.value)">
                    <option value="l" ${quality === 'l' ? 'selected' : ''}>低 (480p15)</option>
                    <option value="m" ${quality === 'm' ? 'selected' : ''}>中 (720p30)</option>
                    <option value="h" ${quality === 'h' ? 'selected' : ''}>高 (1080p60)</option>
                </select>
                <p>Scene名称: ${sceneName}</p>
                <p>渲染文件: ${outputFile}</p>
                <p>源文件: ${filePath}</p>
                <script>
                    const vscode = acquireVsCodeApi();
                    function qualityChanged(value) {
                        vscode.postMessage({ type: 'qualityChanged', quality: value });
                    }
                </script>
            </body>
            </html>
        `;
    }
}